package com.forlove.app.qselect.friend.ui;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.support.v7.widget.AppCompatEditText;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.forlove.app.R;
import com.forlove.app.common.base.ui.BaseActivity;
import com.forlove.app.common.utils.SystemUtils;
import com.forlove.app.common.widget.recyview.BaseRecyclerAdapter;
import com.forlove.app.manager.FriendManager;
import com.forlove.app.manager.NetworkManager;
import com.forlove.app.manager.async.LoadContactsAsync;
import com.forlove.app.qselect.friend.adapter.AddPhoneFriendAdapter;
import com.forlove.app.qselect.friend.adapter.SearchPhoneFriendAdapter;
import com.forlove.app.qselect.friend.entity.ContactsFriendEntity;
import com.forlove.app.qselect.friend.entity.MineFriendEntity;
import com.forlove.app.qselect.friend.entity.NewsFriendsStatus;
import com.forlove.app.qselect.friend.entity.SearchFriendEntity;
import com.forlove.app.qselect.friend.presenter.AddContactsFriendPresenter;
import com.forlove.app.qselect.friend.view.AddContactsFriendView;
import com.forlove.app.qselect.friend.widget.contact.SideBarView;
import com.forlove.app.qselect.index.ui.MineInfoActivity;
import com.forlove.app.qselect.login.entity.ContactsInfoEntity;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.RuntimePermissions;

/**
 * 添加手机联系人
 * Created by yjl on 2017/10/15.
 */

@RuntimePermissions
public class AddContactsFriendActivity extends BaseActivity implements View.OnClickListener,
        TextWatcher, AddContactsFriendView, SideBarView.LetterSelectListener,
        LoaderManager.LoaderCallbacks<List<ContactsInfoEntity>> {

    @BindView(R.id.image_back)
    ImageView image_back;
    @BindView(R.id.tool_view)
    RelativeLayout toolsView;  //toolbar view

    @BindView(R.id.image_search)
    ImageView image_search;  //搜索图标

    @BindView(R.id.view_search)
    RelativeLayout view_search; //搜索框

    @BindView(R.id.edittext_input_query)
    AppCompatEditText edittext_input_query; //输入搜索内容

    @BindView(R.id.text_cancel_query)
    AppCompatTextView text_cancel_query; //取消


    @BindView(R.id.expandale_list_friend)
    ExpandableListView friendListView;  //分组的手机联系人

    @BindView(R.id.list_search_result)
    RecyclerView list_search_result;  //获取搜索结果的页面

    @BindView(R.id.view_side_contacts)
    SideBarView view_side_contacts;

    private AddPhoneFriendAdapter addPhoneFriendAdapter;  //联系人分组list adapter
    private SearchPhoneFriendAdapter searchPhoneFriendAdapter;//搜索结果的recyclerview的adapter
    private List<MineFriendEntity> contactsFriend = new ArrayList<>(); //本地通讯录好友
    private List<MineFriendEntity> friendEntities = new ArrayList<>();//后台返回的好友
    private List<MineFriendEntity> searchFriend = new ArrayList<>();//搜索的好友
    private List<ContactsInfoEntity> contactsInfoEntities = new ArrayList<>();
    private AddContactsFriendPresenter addContactsFriendPresenter;
    private LoadContactsAsync loadContactsAsync;  //异步加载手机通讯录
    private String quryStr; //输入搜索的str
    private String from = "";

    @NeedsPermission(Manifest.permission.READ_CONTACTS)
    void needContacts() {
        getSupportLoaderManager().restartLoader(LoadContactsAsync.ASYNC_ID, null, this);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        AddContactsFriendActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_firend_add_phone;
    }

    @Override
    public void initView() {
        addContactsFriendPresenter = new AddContactsFriendPresenter(this);
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            from = bundle.getString("from");
        }
        image_back.setOnClickListener(this);
        image_search.setOnClickListener(this);
        text_cancel_query.setOnClickListener(this);
        edittext_input_query.addTextChangedListener(this);
        initExpandableGroupAdapter();
        initRecyclerViewAdapter();
        addContactsFriendPresenter.loadContactFriend();
        AddContactsFriendActivityPermissionsDispatcher.needContactsWithPermissionCheck(this);
//        ContactsInfoEntityList infoEntityList = new ContactsInfoEntityList();
//        String contact = ContactsManager.getSaveContactsFriend(this);
//        if (StringUtils.isNotEmpty(contact)) {
//            infoEntityList.parseJSONString(contact);
//            contactsInfoEntities.addAll(infoEntityList.contactsInfoEntities);
//        }
//        contactsInfoEntities.addAll(ContactsManager.getContectInfo(this));
    }

    private LoadContactsAsync createContacts() {
        if (loadContactsAsync == null) {
            loadContactsAsync = new LoadContactsAsync(this);
        }
        return loadContactsAsync;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        getSupportLoaderManager().destroyLoader(LoadContactsAsync.ASYNC_ID);
        if (addPhoneFriendAdapter != null) {
            addPhoneFriendAdapter.clearData();
        }
        if (searchPhoneFriendAdapter != null) {
            searchPhoneFriendAdapter.clearData();
        }
    }

    /**
     * 本地通讯录列表的展示
     */
    private void initExpandableGroupAdapter() {
        addPhoneFriendAdapter = new AddPhoneFriendAdapter(this, addContactsFriendPresenter, contactsFriend);
        friendListView.setAdapter(addPhoneFriendAdapter);
        friendListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
                return true;
            }
        });
        friendListView.setGroupIndicator(null);
        for (int i = 0; i < addPhoneFriendAdapter.getGroupCount(); i++) {
            friendListView.expandGroup(i);
        }
        view_side_contacts.setOnLetterSelectListen(this);
        if (!TextUtils.isEmpty(from)) {
            addPhoneFriendAdapter.setFromViewName(from);
        }
    }


    private void initRecyclerViewAdapter() {
        searchPhoneFriendAdapter = new SearchPhoneFriendAdapter(this,
                R.layout.item_friends_contacts, searchFriend, addContactsFriendPresenter);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        list_search_result.setLayoutManager(linearLayoutManager);
        list_search_result.setAdapter(searchPhoneFriendAdapter);
        searchPhoneFriendAdapter.hideFooterView();
        searchPhoneFriendAdapter.hideEmptyView();
        if (!TextUtils.isEmpty(from)) {
            searchPhoneFriendAdapter.setFromViewName(from);
        }
        searchPhoneFriendAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                if (position < searchFriend.size()) {
                    MineFriendEntity friendEntity = searchFriend.get(position);
                    //添加好友，好友申请页面
                    if (friendEntity.status == NewsFriendsStatus.UNCONFIRM.getCode()
                            || friendEntity.status == NewsFriendsStatus.UNADDED.getCode()
                            || friendEntity.status == NewsFriendsStatus.WAITING.getCode()) {
                        SearchFriendEntity searchFriendEntity = new SearchFriendEntity();
                        searchFriendEntity.friendEntity = friendEntity;
                        searchFriendEntity.isFriend = false;
                        searchFriendEntity.note_times = friendEntity.charm;
                        Intent intent = new Intent(AddContactsFriendActivity.this, SearchUserInfoActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("friendinfo", searchFriendEntity);
                        bundle.putString("mobile", friendEntity.getAvaliableMobile());
                        intent.putExtras(bundle);
                        startActivity(intent);
                    } else if (friendEntity.status == NewsFriendsStatus.CONFIRMED.getCode()) {
                        Intent intent = new Intent(AddContactsFriendActivity.this, MineInfoActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putString("mobile", friendEntity.mobile);
                        intent.putExtras(bundle);
                        startActivity(intent);
                    }
                }
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.image_search:
                if (toolsView.isShown()) {
                    toolsView.setVisibility(View.GONE);
                    view_search.setVisibility(View.VISIBLE);
                    SystemUtils.openInputMethod(this, image_search);
                }
                break;

            case R.id.text_cancel_query:
                view_search.setVisibility(View.GONE);
                edittext_input_query.setText("");
                toolsView.setVisibility(View.VISIBLE);
                SystemUtils.hideKeyBoard(this, text_cancel_query);
                if (!friendListView.isShown()) {
                    friendListView.setVisibility(View.VISIBLE);
                    list_search_result.setVisibility(View.GONE);
                    view_side_contacts.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.image_back:
                onBackPressed();
                break;
        }
    }


    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence text, int start, int before, int count) {


    }

    @Override
    public void afterTextChanged(Editable editable) {
        quryStr = editable.toString().replaceAll(" ", "");
        if (TextUtils.isEmpty(quryStr)) {
            friendListView.setVisibility(View.VISIBLE);
            list_search_result.setVisibility(View.GONE);
            view_side_contacts.setVisibility(View.VISIBLE);
        } else {
            searchFriend.clear();
            searchFriend.addAll(getLocalSearchFriend(quryStr));
            searchPhoneFriendAdapter.setQueryString(quryStr);
            searchPhoneFriendAdapter.updateDatas(searchFriend);
            friendListView.setVisibility(View.GONE);
            view_side_contacts.setVisibility(View.GONE);
            list_search_result.setVisibility(View.VISIBLE);
        }
    }

    private List<MineFriendEntity> getLocalSearchFriend(String queryStr) {
        List<MineFriendEntity> local = new ArrayList<>();
        for (MineFriendEntity friendEntity : contactsFriend) {
            if (friendEntity.contactsName.contains(queryStr)
                    || friendEntity.contactsNumber.contains(queryStr)
                    || (!TextUtils.isEmpty(friendEntity.realname)
                    && friendEntity.realname.contains(queryStr))) {
                local.add(friendEntity);
            }
        }
        return local;
    }

    @Override
    public void onLetterSelected(String letter) {
        setListviewPosition(letter);
    }

    @Override
    public void onLetterChanged(String letter) {
        setListviewPosition(letter);
    }

    @Override
    public void onLetterReleased(String letter) {
        setListviewPosition(letter);
    }

    private void setListviewPosition(String letter) {
        int firstLetterPosition = addPhoneFriendAdapter.getFirstFriendPosition(letter);
        if (firstLetterPosition != -1) {
            friendListView.setSelection(firstLetterPosition);
        }
    }


    @Override
    public Loader<List<ContactsInfoEntity>> onCreateLoader(int id, Bundle args) {
        return createContacts();
    }

    @Override
    public void onLoadFinished(Loader<List<ContactsInfoEntity>> loader, List<ContactsInfoEntity> data) {
        //加载完毕通讯录
        getSupportLoaderManager().destroyLoader(LoadContactsAsync.ASYNC_ID);
        if (data != null) {
            contactsInfoEntities.clear();
            contactsInfoEntities.addAll(data);
            showDataview();
        }
    }

    private void showDataview() {
        contactsFriend.clear();
        contactsFriend.addAll(FriendManager.friendToContacts(friendEntities, contactsInfoEntities));
        addPhoneFriendAdapter.updateFriendList(contactsFriend);
        addPhoneFriendAdapter.notifyDataSetChanged();
        for (int i = 0; i < addPhoneFriendAdapter.getGroupCount(); i++) {
            friendListView.expandGroup(i);
        }
    }

    @Override
    public void onLoaderReset(Loader<List<ContactsInfoEntity>> loader) {

    }

    @Override
    public void showErrorData(NetworkManager.ResultCode resultCode, String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }


    @Override
    public void updateFriendListView(ContactsFriendEntity friendListEntity) {
        if (friendListEntity != null && friendListEntity.concats.size() > 0) {
            friendEntities.clear();
            friendEntities.addAll(friendListEntity.concats);
        }
        showDataview();
    }


}
